from django.shortcuts import render, redirect
from apps.book.models import Publisher
from apps.common.pagination import LxgPageNation


def publisher_list(request):
    """出版社列表"""
    page = LxgPageNation(request, Publisher, 14)
    # publishers = Publisher.objects.all().order_by("-id")
    publishers = page.get_objects()
    page_html = page.get_page_html()
    return render(request, 'book/publisher/list.html', {
        'publishers': publishers,
        'page': page_html
    })


def publisher_add(request):
    """添加出版社"""
    if request.method == 'POST':
        name = request.POST.get("name")
        isbn = request.POST.get("isbn")
        address = request.POST.get("address")
        code = request.POST.get("code")
        telphone = request.POST.get("telphone")
        fax = request.POST.get("fax")
        try:
            # 判断不存在
            Publisher.objects.get(name=name)
        except:
            Publisher.objects.create(
                name=name,
                isbn=isbn,
                address=address,
                code=code,
                telphone=telphone,
                fax=fax
            )
        return redirect('/book/list/')
    return render(request, 'book/publisher/add.html')


def publisher_edit(request):
    """编辑出版社"""
    if request.method == 'POST':
        id = request.POST.get("id")
        name = request.POST.get("name")
        isbn = request.POST.get("isbn")
        address = request.POST.get("address")
        code = request.POST.get("code")
        telphone = request.POST.get("telphone")
        fax = request.POST.get("fax")
        publisher = Publisher.objects.get(id=id)
        publisher.name = name
        publisher.isbn = isbn
        publisher.address = address
        publisher.code = code
        publisher.telphone = telphone
        publisher.fax = fax
        publisher.save()
        return redirect('/book/list/')
    id = request.GET.get("id")
    publisher = Publisher.objects.get(id=id)
    return render(request, 'book/publisher/edit.html', {
        'book': publisher
    })


def publisher_delete(request):
    """删除出版社"""
    id = request.GET.get('id')
    Publisher.objects.get(id=id).delete()
    return redirect('/book/list/')
